package com.fengxu.nio.zerocopy;

import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

// 使用零拷贝技术实现数据复制-客户端
public class NewIOClient {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1",6666));
        while (!socketChannel.finishConnect());
        System.out.println("成功连接到服务器！");

        FileChannel fileChannel = new FileInputStream("E:\\MySoftware\\mima\\1p.txt").getChannel();
//        FileChannel fileChannel = new RandomAccessFile("E:\\MySoftware\\mima\\1p.txt", "rw").getChannel();
        long startTime = System.currentTimeMillis();
        // linux下使用transferTo方法可以完成传输，windows一次只能传输8mb,所以windows需要分段传输
        // transferTo底层使用到了零拷贝
        fileChannel.transferTo(0,fileChannel.size(),socketChannel);
        long endTime = System.currentTimeMillis();
        System.out.println("传输完成共耗时:"+(endTime-startTime)+"ms");

        fileChannel.close();
        socketChannel.close();
    }
}
